package com.crawler.harbour.task;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.crawler.harbour.dto.FZShipmentDto;
import com.crawler.harbour.model.Notice;
import com.crawler.harbour.model.Shipment;
import com.crawler.harbour.model.ShipmentNew;
import com.crawler.harbour.service.INoticeService;
import com.crawler.harbour.service.IShipmentNewService;
import com.crawler.harbour.utils.MapToBeanUtil;
import com.crawler.harbour.utils.RuoKuai;
import com.crawler.harbour.utils.StorageDay;
import com.crawler.harbour.utils.StringUtils;
import com.crawler.harbour.utils.UrlUtil;
import com.crawler.utils.BeanUtils;
import com.crawler.utils.RedisManager;

import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

@Component
@Lazy(false)
public class FZcqTask extends StorageDay{

	@Autowired
    IShipmentNewService shipmentNewService;

    @Autowired
    private INoticeService noticeService;

    //江阴港
    @Scheduled(cron = "0 0 0/2 * * ?")
    public void fzpuJYShip(){
    	if(!RedisManager.lock("ship:fzpuJYShip", 0)) {
    		return;
    	}
        FZShipmentDto fzShipmentDto = new FZShipmentDto();
 		fzShipmentDto.setDomain("FIC");
		fzShipmentDto.setSailoff("N");
        fzShipment(fzShipmentDto);
        fzShipmentDto.setSailoff("Y");
        fzShipment(fzShipmentDto);
    }

    //青州港
    @Scheduled(cron = "0 0 0/2 * * ?")
    public void fzpuQZShip(){
    	if(!RedisManager.lock("ship:fzpuQZShip", 0)) {
    		return;
    	}
        FZShipmentDto fzShipmentDto = new FZShipmentDto();
        fzShipmentDto.setDomain("FQC");
        fzShipmentDto.setSailoff("N");
        fzShipment(fzShipmentDto);
        fzShipmentDto.setSailoff("Y");
        fzShipment(fzShipmentDto);
        
    }

    //shipment 表的内容
    private void fzShipment(FZShipmentDto fzShipmentDto){
        JSONObject jsonObject = JSONUtil.parseObj(fzShipmentDto);
        jsonObject.put("page", 1);
        jsonObject.put("rows", 10000);
        
        StringBuilder url = new StringBuilder(UrlUtil.FZPU);
        url.append("?");
    	if (MapUtil.isNotEmpty(jsonObject)) {
			for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
				url.append(entry.getKey()).append("=").append( entry.getValue()).append("&");
			}
		}
        String result = HttpUtil.post(url.substring(0,url.length()-1),new HashMap<String, Object>());
        Map<String,Object> resultMap = JSON.parseObject(result);
        JSONArray rows = JSON.parseArray(resultMap.get("rows").toString());
        List<String> IdList =new ArrayList<>();
        for (Object row:rows){
        	ShipmentNew shipmentNew = new ShipmentNew();
        	Date date = new Date();
            Map<String,Object> rowMap = JSON.parseObject(row.toString());
            Shipment shipment = MapToBeanUtil.shipment(rowMap);
            String hashStr = null;            
            Notice notice = new Notice();
            if ("FIC".equals(shipment.getWharfName())){
            	hashStr = RuoKuai.MD5("FIC"+shipment.getVslNameEn()+shipment.getInVvd()+"_1");
                notice.setPortNo("FIC");
                shipmentNew.setWharfName("福州江阴港");
            }else {
            	hashStr = RuoKuai.MD5("FQC"+shipment.getVslNameEn()+shipment.getInVvd()+"_1");
                notice.setPortNo("FQC");
                shipmentNew.setWharfName("福州青州港");
            }
            shipment.setId(hashStr);
            shipmentNew.setId(hashStr);
            ShipmentNew temp = shipmentNewService.selectById(hashStr);
            notice.setShipName(StringUtils.nuller(shipment.getVslNameEn()));
            notice.setShipCnName(StringUtils.nuller(shipment.getVslNameCn()));
            notice.setJkShipTimer(StringUtils.nuller(shipment.getInVvd()));
            notice.setCkShipTimer(StringUtils.nuller(shipment.getOutVvd()));
            notice.setJkSailingDate(timeStamp2Date(shipment.getEta()));
            notice.setCkSailingDate(convertTime(shipment.getSailingDate()));
            notice.setIntoDate(convertTime(shipment.getCyRcvDate()));
            notice.setOffDate(convertTime(shipment.getCyCutDate()));
            notice.setBerthDate(convertTime(shipment.getBerthingDate()));
            notice.setLeaveDate(convertTime(shipment.getSailingDate()));
            notice.setCutOffDate(convertTime(shipment.getCustCutDate()));
            notice.setStatus(0);
            if(StringUtils.isBlank(notice.getShipName())) {
            	notice.setShipName(notice.getShipCnName());
            }
            notice.setCreateTime(date);
            shipmentNew.setType(1);
            shipmentNew.setShipTimer(StringUtils.nuller(shipment.getInVvd()));
            BeanUtils.copyProperties(notice,shipmentNew , "id","status","type","shipTimer","sailingDate");
            shipmentNew.setSailingDate(notice.getJkSailingDate());
            shipmentNewService.insertOrUpdateAllColumn(shipmentNew);
            if("FIC".equals(shipmentNew.getPortNo())){
            	hashStr = RuoKuai.MD5("FIC"+shipment.getVslNameEn()+shipment.getOutVvd()+"_2");
            }else {
            	hashStr = RuoKuai.MD5("FQC"+shipment.getVslNameEn()+shipment.getOutVvd()+"_2");
            }            
            ShipmentNew temp2 = shipmentNewService.selectById(hashStr);
            shipmentNew.setId(hashStr);
            shipmentNew.setType(2);
            shipmentNew.setShipTimer(shipment.getOutVvd());    
            shipmentNew.setSailingDate(notice.getCkSailingDate());
            shipmentNewService.insertOrUpdateAllColumn(shipmentNew);
            boolean isOk = true;
		    if(temp!=null&&IdList.contains(temp.getId())||temp2!=null&&IdList.contains(temp2.getId())) {
		        isOk = false;
		    }
            if(isOk) {
	                if(temp!=null&&!temp.getSailingDate().equals(timeStamp2Date(shipment.getEta()))){
	                	if(temp.getSailingDate().equals("")) {
	                		notice.setType(0);
	                	}else {
	                		notice.setType(4);
	                	}
	                    notice.setId(null);
	                    notice.setOrigValue(temp.getSailingDate());
	                    noticeService.insert(notice);
	                } 
	                if(temp2!=null&&!temp2.getOffDate().equals(shipmentNew.getOffDate())){
	                    notice.setType(2);
	                    notice.setId(null);
	                    notice.setOrigValue(temp.getOffDate());
	                    noticeService.insert(notice);
	                }
	               if(temp2!=null&&!temp2.getIntoDate().equals(shipmentNew.getIntoDate())){
	                    notice.setType(3);
	                    notice.setId(null);
	                    notice.setOrigValue(temp.getIntoDate());
	                    noticeService.insert(notice);
	                }
	               if(temp!=null) {
		            	IdList.add(temp.getId());
		            }
		           if(temp2!=null) {
		            	IdList.add(temp2.getId());
		            }
            }
        }
    }
    
	public static String timeStamp2Date(String seconds) {
		if (seconds == null || seconds.isEmpty() || seconds.equals("null")) {
			return "";
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		return sdf.format(new Date(Long.valueOf(seconds)));
	}
	
	 private String convertTime(String date) {
	    	if(date == null || "".equals(date)) {
	    		return "";
	    	}
	    	return date.substring(0,date.lastIndexOf(":"));
	    	
	    }
	 
	
}
